function getTempleList(){
    var api = "/backstage/temples/list";
    $.ajax({
        url: api,
        type: "GET",
        success: function(data, status){
            if(data.status == 200) {
                var temples = data.data;
                $("#templeDataTable").DataTable({
                    data: temples,
                    destroy: true,
                    columnDefs: [
                        {
                            "targets": "templeID",
                            "data": "id",
                        },
                        {
                            "targets": "templeName",
                            "data": "name",
                        },
                        {
                            "targets": "templeImage",
                            "data": "img_url",
                            "render": function(data, type, row){
                                if(type == "display") {
                                    return "<img src='" + data + "' style='height:50px;'>";
                                }
                                return data;
                            },
                        },
                        {
                            "targets": "templeOperation",
                            "defaultContent": 
                            '<button class="btn btn-primary btn-xs templeDetail">编辑</button>' +
                            '<button class="btn btn-danger btn-xs templeDelete">删除</button>',
                        },
                    ],
                });
            }
            else {
                alert("请求异常，请刷新");
            }
        },
    })
}

function getTempleDetail(templeID, uploaded){
    var api = "/backstage/temples/" + templeID;
    $.ajax({
        url: api,
        type: "GET",
        success: function(data, status){
            if(data.status == 200) {
                var temple = data.data;
                $("#nameInput").val(temple.name);

                var imgUrl = temple.img_url;
                var mockFile = { name: "Filename", size: 12345 };
                var myDropzone = Dropzone.forElement("#myDropzone");
                myDropzone.emit("addedfile", mockFile);
                myDropzone.emit("thumbnail", mockFile, imgUrl);
                myDropzone.emit("complete", mockFile);
                var existingFileCount = 1; // The number of files already uploaded
                myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
                uploaded.push(imgUrl);


            }
            else {
                alert("请求异常，请刷新");
            }
        },
    })
}

function deleteTemple(templeID){
    var api = "/backstage/temples/" + templeID;
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: api,
        type: "DELETE",
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status == 200) {
                console.log("请求成功");
            }
            else {
                alert("请求异常，请刷新");
            }
        }
    })
}

function initTempleList(){
    getTempleList();
    $('#templeDataTable').on('click', 'button', function () {
        var table = $("#templeDataTable").DataTable();
        var templeID = table.row($(this).parents('tr')).data().id;
        var actionName = $(this)[0].classList[3];

        if(actionName == "templeDelete"){
            var r = confirm("是否删除施愿处？");
            if (r == true){
                deleteTemple(templeID);
                getTempleList();
            }
        }
        else if(actionName == "templeDetail"){
            var href = "temple_detail.html" + "?templeID=" + templeID + "&mode=update";
            window.location.href = href;
        }

    } );
}

function createTemple(name, imgUrl){
    var api = "/backstage/temples/list";
    var data = {
        "name": name,
        "img_url": imgUrl,
    };
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: api,
        type: "POST",
        data: data,
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status == 200) {
                console.log("请求成功");
                var href = "temple_list.html";
                window.location.href = href;
            }
            else {
                alert("请求异常，请刷新");
            }
        }
    });
}

function updateTemple(id, name, imgUrl){
    var api = "/backstage/temples/" + id;
    var data = {
        "name": name,
        "img_url": imgUrl,
    };
    var csrftoken = getCookie('csrftoken');
    $.ajax({
        url: api,
        type: "PUT",
        data: data,
        beforeSend: function(xhr, settings) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        },
        success: function(data, status){
            if(data.status == 200) {
                console.log("请求成功");
                var href = "temple_list.html";
                window.location.href = href;
            }
            else {
                alert("请求异常，请刷新");
            }
        }
    });

}


function initTempleDetail() {
    var templeID = getQueryString("templeID");
    var mode = getQueryString("mode");

    Dropzone.autoDiscover = false;
    var uploaded = [];
    var csrftoken = getCookie('csrftoken');
    var myDropzone = new Dropzone("div#myDropzone",{
            url: "/backstage/common/image/upload",
            maxFiles: 1,
            addRemoveLinks: true,
            headers: {
                "X-CSRFTOKEN": csrftoken,
            },
            maxfilesexceeded: function(file) {
                uploaded.pop();
                this.removeAllFiles();
                // this.addFile(file);
            },
            success: function(file, response){
                uploaded.push(response.data.img_url);
            },
            dictDefaultMessage: "拖拽文件到此处上传",
            dictRemoveFile: "移除文件",
        });

    if(mode == "update"){
        getTempleDetail(templeID, uploaded);
        var isCreate = false;
    }
    else{
        var isCreate = true;
    }

    $('#saveTempleBtn').on('click', function () {
        if(uploaded.length == 0){
            alert("缺少图片");
            return;
        }
        var name = $("#nameInput").val();
        var imgUrl = uploaded[0];
        console.log(isCreate)
        if(isCreate){
            createTemple(name, imgUrl);
        }
        else{
            updateTemple(templeID, name, imgUrl);
        }
    });
}

function init() {
    var parts = window.location.pathname.split("/");
    var lastPart = parts[parts.length - 1];

    var initFuncMap = {
        "temple_list.html": initTempleList,
        "temple_detail.html": initTempleDetail,
    };

    var initFunc = initFuncMap[lastPart];
    initFunc();
}

$(function(){
    init();
})
